package android.tusnotas.core;

import android.tusnotas.beans.PushStatus;
import android.tusnotas.connector.webservice.WebServiceCaller;
import android.tusnotas.exception.ProcessingInstancesException;
import android.tusnotas.exception.RemoteReadingException;
import android.tusnotas.parser.subscription.PushSubscriptionParser;
import android.tusnotas.util.Devel;
import android.util.Log;

public class PushSubscriptionAnalyser {
	
		private WebServiceCaller caller = new WebServiceCaller();

		private int ttt = 5;//times to try before giving up connection try
		
		public PushStatus doSubscription(String appId, String androidId) throws RemoteReadingException, ProcessingInstancesException{
			String XML = doGetSubscription(appId, androidId);
			PushStatus ps = doObtainSubscription(XML);
			return ps;
		}

		private PushStatus doObtainSubscription(String XML) throws ProcessingInstancesException{
			PushStatus ps = null;
			
			PushSubscriptionParser subscriptionParser = new PushSubscriptionParser();
			try {
				ps = subscriptionParser.parseXML(XML);
			} catch (Exception e) {
				e.printStackTrace();
				throw new ProcessingInstancesException();
			}
			return ps;
		}

		private String doGetSubscription(String appId, String androidId) throws RemoteReadingException{
			String XML="";
			try {
				caller.setPushSubscription(appId, androidId);
				XML = persistentCaller();
			} catch (Exception e) {
				if( Devel.fullDevel){
					Log.w(this.getClass().getName(), "ERROR WHILE CONNECTING TO WC");
				}
				RemoteReadingException rwce = new RemoteReadingException();
				rwce.setErrorCode(GradeAnalyserStatuses.WEIRD_FAILURE);
				throw rwce;
			}
			return XML;
		}
		
		private String persistentCaller() throws RemoteReadingException{	
			while( ttt > 0){
				try{
					String XML = caller.execute();
					return XML;
				}catch(RemoteReadingException e){}
				ttt--;
			}
			throw new RemoteReadingException();
		}
	}

